package me.pplay.playtalk.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import me.pplay.playtalk.protocol.bean.KeyValue;
import me.pplay.playtalk.util.SkyUtil;

import org.apache.http.util.EncodingUtils;

public class IniDb {
	private String filename;
	private ArrayList<KeyValue> list = new ArrayList<KeyValue>();

	public IniDb(String filename) {
		this.filename = filename;
		String filedata = readFileSdcard(filename);
		if (filedata != null && filedata.length() > 0) {
			String[] values = filedata.split("\n");
			for (int i = 0; i < values.length; i++) {
				String[] value2 = values[i].split("\r");
				KeyValue kv = new KeyValue();
				kv.key = SkyUtil.Base64decode(value2[0]);
				kv.value = SkyUtil.Base64decode(value2[1]);
				list.add(kv);
			}

		}

	}

	public void add(String key, String value) {
		KeyValue kv = find(key);
		if (kv == null) {
			kv = new KeyValue();
			kv.key = key;
			kv.value = value;
			list.add(kv);
		} else {
			kv.value = value;
		}

	}

	private KeyValue find(String key) {
		for (KeyValue kv : list) {
			if (kv.key.equals(key)) {
				return kv;
			}
		}
		return null;
	}

	public boolean del(String key) {
		for (KeyValue kv : list) {
			if (kv.key.equals(key)) {
				list.remove(kv);
				return true;
			}
		}
		return false;
	}

	public void commit() {
		File file = new File(filename);
		if (file.exists())
			file.delete();
		String value = "";
		for (KeyValue kv : list) {
			value += SkyUtil.Base64encode(kv.key) + "\r" + SkyUtil.Base64encode(kv.value) + "\n";
		}
		writeFileSdcard(filename, value);
	}

	public ArrayList<KeyValue> getAll() {
		return list;
	}

	// 读在/mnt/sdcard/目录下面的文件
	private String readFileSdcard(String fileName) {
		String res = "";
		try {
			FileInputStream fin = new FileInputStream(fileName);
			int length = fin.available();
			byte[] buffer = new byte[length];
			fin.read(buffer);
			res = EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	// 写在/mnt/sdcard/目录下面的文件
	private void writeFileSdcard(String fileName, String message) {
		try {
			FileOutputStream fout = new FileOutputStream(fileName);
			byte[] bytes = message.getBytes("UTF-8");
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
